﻿// MedicalRulesEngine.API/Controllers/MetadataController.cs
using Microsoft.AspNetCore.Mvc;
using MedicalRulesEngine.Core.Services;
using MedicalRulesEngine.Core.DTOs;

namespace MedicalRulesEngine.API.Controllers;

/// <summary>
/// 元数据管理控制器
/// 提供字段定义、操作符定义等元数据查询功能
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Tags("元数据管理")]
public class MetadataController : BaseController
{
    private readonly IMetadataService _metadataService;
    private readonly ILogger<MetadataController> _logger;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="metadataService">元数据服务</param>
    /// <param name="logger">日志记录器</param>
    public MetadataController(IMetadataService metadataService, ILogger<MetadataController> logger)
    {
        _metadataService = metadataService ?? throw new ArgumentNullException(nameof(metadataService));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    /// <summary>
    /// 获取所有字段定义
    /// </summary>
    /// <returns>字段定义列表</returns>
    [HttpGet("fields")]
    [ProducesResponseType(typeof(ApiResponse<IEnumerable<FieldDefinitionDto>>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 500)]
    public async Task<IActionResult> GetAllFieldDefinitions()
    {
        try
        {
            var fieldDefinitions = await _metadataService.GetAllFieldDefinitionsAsync();
            return Success(fieldDefinitions, "获取字段定义列表成功");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取所有字段定义时发生错误");
            return Error("获取字段定义列表失败", 500);
        }
    }

    /// <summary>
    /// 根据分类获取字段定义
    /// </summary>
    /// <param name="category">分类</param>
    /// <returns>字段定义列表</returns>
    [HttpGet("fields/by-category/{category}")]
    [ProducesResponseType(typeof(ApiResponse<IEnumerable<FieldDefinitionDto>>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 400)]
    [ProducesResponseType(typeof(ApiResponse), 500)]
    public async Task<IActionResult> GetFieldDefinitionsByCategory([FromRoute] string category)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(category))
                return Error("分类不能为空");

            var fieldDefinitions = await _metadataService.GetFieldDefinitionsByCategoryAsync(category);
            return Success(fieldDefinitions, $"获取分类 {category} 的字段定义列表成功");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "根据分类获取字段定义时发生错误，Category: {Category}", category);
            return Error("获取字段定义列表失败", 500);
        }
    }

    /// <summary>
    /// 获取所有操作符定义
    /// </summary>
    /// <returns>操作符定义列表</returns>
    [HttpGet("operators")]
    [ProducesResponseType(typeof(ApiResponse<IEnumerable<OperatorDefinitionDto>>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 500)]
    public async Task<IActionResult> GetAllOperatorDefinitions()
    {
        try
        {
            var operatorDefinitions = await _metadataService.GetAllOperatorDefinitionsAsync();
            return Success(operatorDefinitions, "获取操作符定义列表成功");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取所有操作符定义时发生错误");
            return Error("获取操作符定义列表失败", 500);
        }
    }

    /// <summary>
    /// 根据数据类型获取支持的操作符
    /// </summary>
    /// <param name="dataType">数据类型</param>
    /// <returns>操作符定义列表</returns>
    [HttpGet("operators/by-datatype/{dataType}")]
    [ProducesResponseType(typeof(ApiResponse<IEnumerable<OperatorDefinitionDto>>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 400)]
    [ProducesResponseType(typeof(ApiResponse), 500)]
    public async Task<IActionResult> GetOperatorsByDataType([FromRoute] string dataType)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(dataType))
                return Error("数据类型不能为空");

            var operatorDefinitions = await _metadataService.GetOperatorsByDataTypeAsync(dataType);
            return Success(operatorDefinitions, $"获取数据类型 {dataType} 支持的操作符列表成功");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "根据数据类型获取操作符时发生错误，DataType: {DataType}", dataType);
            return Error("获取操作符列表失败", 500);
        }
    }

    /// <summary>
    /// 获取规则编辑器配置
    /// </summary>
    /// <returns>编辑器配置</returns>
    [HttpGet("editor-config")]
    [ProducesResponseType(typeof(ApiResponse<RuleEditorConfig>), 200)]
    [ProducesResponseType(typeof(ApiResponse), 500)]
    public async Task<IActionResult> GetRuleEditorConfig()
    {
        try
        {
            var config = await _metadataService.GetRuleEditorConfigAsync();
            return Success(config, "获取规则编辑器配置成功");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取规则编辑器配置时发生错误");
            return Error("获取规则编辑器配置失败", 500);
        }
    }

    /// <summary>
    /// 初始化默认元数据
    /// </summary>
    /// <returns>操作结果</returns>
    [HttpPost("initialize")]
    [ProducesResponseType(typeof(ApiResponse), 200)]
    [ProducesResponseType(typeof(ApiResponse), 500)]
    public async Task<IActionResult> InitializeDefaultMetadata()
    {
        try
        {
            await _metadataService.InitializeDefaultMetadataAsync();
            return Success("初始化默认元数据成功");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "初始化默认元数据时发生错误");
            return Error("初始化默认元数据失败", 500);
        }
    }
}


